import pyaudio, wave, sys, optparse, datetime
import utils

__author__ = 'Emmet Connolly (emmetc@thoughtwax.com)'
__version__ = '0.1'
__date__ = '2007/09/30'



# Used to uniquely tag each user's files.
username = ''



# DEPRECATED: REPLACED WITH FUNCTION IN UTILS
# Only use for testing where live GPS data is not available.
def getLocation():
  # Dummy GPS values (St.Stephen's Green, Dublin).
  lat = '53.337997'
  lon = '-6.25924'
  return lat, lon



def main(argv):
  """
  Sets up user data and prompts the user to begin recording.
  """

  global username

  # Display the welcome message.
  print 'Adaptive Spaces v' + __version__
  print 'Press Ctrl+C at any time to quit'

  # Parse command line arguments, and prompt or set defaults if none
  # were provided.
  parser = optparse.OptionParser()
  parser.add_option('-u',
                    '--username',
                    dest = 'username',
                    default = '',
                    type = 'string',
                    help = 'Arbritrary username of the participant')
  (options, args) = parser.parse_args()

  # Prompt for a username if none was provided as a command line
  # argument.
  if options.username == '':
    username = raw_input('Enter username: ')
  else:
    username = options.username

  # Setup is finished, prompt the user to begin recording.
  promptRecording()



def promptRecording():
  """
  Prompt the user to start a recording by entering keyboard input.
  This could be a lot better if the event that triggered recording
  was less reliant on the keyboard input.
  """

  input = raw_input('Press enter to start recording')
  if input == '':
    # Create a datestamp to be used in the filename.
    now = datetime.datetime.now()
    # Create location string to be used in filename. This is a simple
    # method of geocoding each file without having to deal with file
    # metadata..
    pos = utils.getLocation()
    posString = 'lat' + str(pos[0]) + 'lon' + str(pos[1])
    print posString
    # Play an audio message to indicate that recording has started.
    utils.play('started.wav')
    record(now.strftime("%Y%m%dT%H%M%S"), posString)
  else:
    promptRecording()



def record(timestamp, pos):
  """
  Records audio input to an external wav file, the name of which is a
  combination of the username, the current time, and the current GPS
  position, separated by underscores, e.g.:
  emmet_20070910T211954_lat1234.123lon5678.567.wav
  """

  global username

  # Define some recording settings constants.
  chunk = 1024
  FORMAT = pyaudio.paInt16
  CHANNELS = 1
  RATE = 44100
  RECORD_SECONDS = 30
  # Build the name of the file about to be recorded.
  WAVE_OUTPUT_FILENAME = username + '_' + timestamp + '_' + pos + '.wav'

  p = pyaudio.PyAudio()
  stream = p.open(format = FORMAT,
                  channels = CHANNELS,
                  rate = RATE,
                  input = True,
                  frames_per_buffer = chunk)

  print "* recording"
  all = []
  for i in range(0, RATE / chunk * RECORD_SECONDS):
    data = stream.read(chunk)
    all.append(data)
  print "* done recording"
  stream.close()
  p.terminate()

  # write data to WAVE file
  data = ''.join(all)
  wf = wave.open(utils.mediaDirectory + '/' + WAVE_OUTPUT_FILENAME, 'wb')
  wf.setnchannels(CHANNELS)
  wf.setsampwidth(p.get_sample_size(FORMAT))
  wf.setframerate(RATE)
  wf.writeframes(data)
  wf.close()

  # Notify the user that the recording has stopped.
  utils.play('stopped.wav')
  # Done recording audio clip, prompt user to start again.
  promptRecording()



# Get walking.
if __name__ == '__main__':
  main(sys.argv[1:])
